package com.ccubee.data.transfer.transfer.mod.impl;


import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.ExceptionUtils;
import com.ccubee.data.transfer.event.ColumnData;
import com.ccubee.data.transfer.event.IEventType;
import com.ccubee.data.transfer.event.SqlData;
import com.ccubee.data.transfer.transfer.mod.AbstractMod;
import com.ccubee.data.transfer.transfer.mod.Imod;
import com.ccubee.data.transfer.types.TransferMod;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;

/**
 * ID模式
 *
 * @Author ycf
 * @Date 2022/11/14 14:37
 * @Version 1.0
 */
@Component
@Slf4j
public class IdMod extends AbstractMod implements Imod {

    @Override
    public TransferMod mod() {
        return TransferMod.ID;
    }

    @Override
    protected SqlData sqlData(String dbName, String tableName, long num) {
        return SqlData.builder()
                .sql(String.format(IEventType.SELECT_SQL, dbName, tableName, mod().sql(transferRequest)))
                .data(Lists.newArrayList(num, transferRequest.getPageSize()))
                .build();
    }

    @Override
    protected long num(List<List<ColumnData>> maps, long num) {
        if (CollUtil.isEmpty(maps)) {
            return -1;
        }
        Object value = maps.get(maps.size() - 1)
                .stream()
                .filter(i -> i.getName().equals(transferRequest.getColumn()))
                .findFirst()
                .orElseThrow(() -> ExceptionUtils.mpe("未匹配到字段" + transferRequest.getColumn()))
                .getValue();
        if (Objects.isNull(value)) {
            log.warn("num value is null,name:{},value:{}", transferRequest.getColumn(), maps);
        }
        return Objects.requireNonNull(value, "匹配到到数据为空") instanceof Long ? (Long) value : Long.parseLong(value.toString());
    }
}
